// src/store/student.js
// 学生状态管理
import { defineStore } from 'pinia'
import apiClient from '../api'
import { studentApi } from '../api/student'

export const useStudentStore = defineStore('student', {
    state: () => ({
        profile: null,
        applications: [],
        positions: [],
        materials: [],
        evaluations: []
    }),

    actions: {
        // 获取学生个人信息
        async fetchProfile() {
            try {
                const response = await apiClient.get('/student/profile')
                this.profile = response.data
                return response.data
            } catch (error) {
                // 更详细的错误信息记录
                console.error('获取学生信息失败:', {
                    status: error.response?.status,
                    statusText: error.response?.statusText,
                    message: error.response?.data?.message || error.message
                })
                throw new Error(error.response?.data?.message || '获取学生信息失败')
            }
        },

        // 获取用户信息（包括邮箱和电话）
        async fetchUserProfile() {
            try {
                const response = await apiClient.get('/user/profile')
                return response.data
            } catch (error) {
                console.error('获取用户信息失败:', {
                    status: error.response?.status,
                    statusText: error.response?.statusText,
                    message: error.response?.data?.message || error.message
                })
                throw new Error(error.response?.data?.message || '获取用户信息失败')
            }
        },

        // 注册学生个人信息
        async registerStudentProfile(data) {
            try {
                const response = await apiClient.post('/student/register', data)
                this.profile = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '注册学生信息失败')
            }
        },

        // 更新学生个人信息
        async updateProfile(data) {
            try {
                const response = await apiClient.put('/student/profile', data)
                this.profile = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新学生信息失败')
            }
        },

        // 更新用户信息（包括邮箱和电话）
        async updateUserProfile(data) {
            try {
                const response = await apiClient.put('/user/profile', data)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新用户信息失败')
            }
        },

        // 获取实习申请列表
        async fetchApplications(params = {}) {
            try {
                const response = await apiClient.get('/internship-applications/my', { params })
                this.applications = response.data.content || response.data
                return response.data
            } catch (error) {
                // 不抛出异常，而是返回空数组
                console.error('获取申请列表失败:', error)
                return { content: [], totalElements: 0 }
            }
        },

        // 获取实习申请详情
        async fetchApplicationDetail(applicationId) {
            try {
                const response = await apiClient.get(`/internship-applications/${applicationId}`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取申请详情失败')
            }
        },

        // 取消实习申请
        async cancelApplication(applicationId) {
            try {
                const response = await apiClient.put(`/internship-applications/${applicationId}/cancel`)
                // 更新本地申请列表
                const index = this.applications.findIndex(app => app.id === applicationId)
                if (index !== -1) {
                    this.applications[index] = response.data.application
                }
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '取消申请失败')
            }
        },

        // 提交实习申请
        async submitApplication(data) {
            try {
                const response = await apiClient.post('/internship-applications', data)
                this.applications.unshift(response.data)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '提交申请失败')
            }
        },

        // 获取实习岗位列表
        async fetchPositions(params = {}) {
            try {
                const response = await apiClient.get('/internship-positions', { params })
                this.positions = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取岗位列表失败')
            }
        },

        // 获取实习材料列表
        async fetchMaterials() {
            try {
                const response = await apiClient.get('/internship-materials/my')
                this.materials = response.data.content || response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取材料列表失败')
            }
        },

        // 提交实习材料
        async submitMaterial(data) {
            try {
                const response = await studentApi.submitMaterial(data)
                // 添加到材料列表开头
                if (this.materials && Array.isArray(this.materials)) {
                    this.materials.unshift(response.data)
                }
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '提交材料失败')
            }
        },

        // 获取我的实习信息（新添加的方法）
        async fetchMyInternships() {
            try {
                const response = await apiClient.get('/internships/my')
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取实习信息失败')
            }
        },

        // 获取实习最终成绩评定（新添加的方法）
        async getFinalEvaluation(internshipId) {
            try {
                const response = await apiClient.get(`/student/internships/${internshipId}/final-evaluations`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取实习成绩失败')
            }
        },

        // 添加新的store action
        async fetchStudentInternships(studentId) {
            try {
                const response = await studentApi.getStudentInternships(studentId)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取学生实习信息失败')
            }
        },

        // 获取材料详情
        async getMaterialDetail(materialId) {
            try {
                const response = await studentApi.getMaterialDetail(materialId)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取材料详情失败')
            }
        },

        // 更新实习材料
        async updateMaterial(materialId, data) {
            try {
                const response = await studentApi.updateMaterial(materialId, data)
                // 更新本地材料列表
                const index = this.materials.findIndex(material => material.id === materialId)
                if (index !== -1) {
                    this.materials[index] = response.data
                }
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新材料失败')
            }
        },

        // 删除实习材料
        async deleteMaterial(materialId) {
            try {
                await studentApi.deleteMaterial(materialId)
                // 从本地材料列表中移除
                this.materials = this.materials.filter(material => material.id !== materialId)
                return true
            } catch (error) {
                throw new Error(error.response?.data?.message || '删除材料失败')
            }
        },

        // 获取成绩评价
        async fetchEvaluations() {
            try {
                const response = await apiClient.get('/evaluations/my')
                this.evaluations = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取评价信息失败')
            }
        }
    }
})
